<template>
  <el-card>
    <template #header>
      <div style="display:flex;gap:12px;align-items:center;">
        <el-input v-model="query.graphicName" placeholder="graphic_name" style="width:260px"/>
        <el-button type="primary" @click="load">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button type="success" @click="openEdit()">新增</el-button>
        <el-button type="danger" :disabled="!multipleSelection.length" @click="batchRemove">批量删除</el-button>
      </div>
    </template>

    <el-table :data="list" @selection-change="multipleSelection=$event">
      <el-table-column type="selection" width="48"/>
      <el-table-column prop="id" label="ID" width="80"/>
      <el-table-column prop="graphicName" label="graphic_name"/>
      <el-table-column prop="desc" label="描述"/>
      <el-table-column prop="updateTime" label="update_time"/>
      <el-table-column label="操作" width="260">
        <template #default="{row}">
          <el-button size="small" @click="openEdit(row)">编辑</el-button>
          <el-button size="small" @click="view(row.id)">查看/编辑SVG</el-button>
          <el-button size="small" type="danger" @click="remove(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="page.pageNum"
      v-model:page-size="page.pageSize"
      :total="page.total"
      layout="prev, pager, next, jumper, total, sizes"
      :page-sizes="[10,20,50,100]"
      @current-change="load"
      @size-change="load"
      class="mt-3"
    />

    <el-dialog v-model="visible" :title="form.id ? '编辑' : '新增'" width="800px">
      <el-form :model="form" label-width="140px">
        <el-form-item label="graphic_name"><el-input v-model="form.graphicName"/></el-form-item>
        <el-form-item label="desc"><el-input v-model="form.desc"/></el-form-item>
        <el-form-item label="svg(base64)"><el-input type="textarea" :rows="6" v-model="form.svg"/></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="visible=false">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </template>
    </el-dialog>

    <el-drawer v-model="drawer" title="SVG预览/编辑" size="70%">
      <div style="display:flex; gap:16px; height:100%;">
        <el-card style="flex:1; display:flex; flex-direction:column;">
          <template #header>SVG文本（可编辑）</template>
          <el-input v-model="svgText" type="textarea" :rows="20" placeholder="在此编辑SVG文本..." style="flex:1;"/>
          <div style="margin-top:8px; display:flex; gap:8px;">
            <el-button @click="refreshPreview">刷新预览</el-button>
            <el-button type="primary" @click="saveSvgText" :disabled="!currentId">保存到数据库</el-button>
          </div>
        </el-card>
        <el-card style="flex:1;">
          <template #header>SVG渲染（黑色背景）</template>
          <div v-html="previewHtml" style="border:1px solid #333; padding:8px; max-height:70vh; overflow:auto; background:#000;"></div>
        </el-card>
      </div>
    </el-drawer>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const list = ref<any[]>([])
const page = reactive({ pageNum: 1, pageSize: 10, total: 0 })
const query = reactive({ graphicName: '' })
const visible = ref(false)
const form = reactive<any>({})
const multipleSelection = ref<any[]>([])

const drawer = ref(false)
const svgText = ref('')
const previewHtml = ref('')
const currentId = ref<number | null>(null)
const currentRecord = ref<any>(null)

watch(svgText, (val)=>{ previewHtml.value = val || '' })

async function load() {
  const { data } = await axios.get('/api/admin/graphicsLibrary/page', { params: { pageNum: page.pageNum, pageSize: page.pageSize, graphicName: query.graphicName } })
  list.value = data.records || []
  page.total = data.total || 0
}
function reset(){ Object.assign(query, { graphicName:'' }); load() }
function openEdit(row?: any){ Object.assign(form, row||{}); visible.value=true }
async function submit(){ if(form.id){ await axios.put('/api/admin/graphicsLibrary', form) } else { await axios.post('/api/admin/graphicsLibrary', form) } visible.value=false; load() }
async function remove(id:number){ await axios.delete(`/api/admin/graphicsLibrary/${id}`); load() }
async function batchRemove(){ await axios.post('/api/admin/graphicsLibrary/batchDelete', multipleSelection.value.map(x=>x.id)); load() }

async function view(id:number){
  const { data } = await axios.get(`/api/admin/graphicsLibrary/${id}`)
  currentId.value = id
  currentRecord.value = data.data || null
  svgText.value = data.svgText || ''
  previewHtml.value = svgText.value
  drawer.value = true
}

function refreshPreview(){ previewHtml.value = svgText.value }

function encodeBase64Utf8(str:string){
  try {
    return btoa(unescape(encodeURIComponent(str)))
  } catch {
    // 兼容极端字符
    const bytes = new TextEncoder().encode(str)
    let binary = ''
    bytes.forEach(b=> binary += String.fromCharCode(b))
    return btoa(binary)
  }
}

async function saveSvgText(){
  if(!currentId.value || !currentRecord.value){ ElMessage.error('无有效记录'); return }
  const updated = { ...currentRecord.value, svg: encodeBase64Utf8(svgText.value || '') }
  await axios.put('/api/admin/graphicsLibrary', updated)
  ElMessage.success('已保存')
  load()
}

onMounted(load)
</script>
